import utils from "../../assets/utils/utils";
import {aria2cPort} from "../../config";

const state = {
	path: `ws://localhost:${aria2cPort}/jsonrpc`,
	socketReady: false,
	socket: null,
	downloadFileList: [],
	raw: [],
	magStatus: {
		'aria2.onDownloadStart': 1,//开始
		'aria2.onDownloadPause': -1,//暂停
		'aria2.onDownloadComplete': 2,//完成
		'aria2.onDownloadError': -9, //下载错误
		// 'aria2.onDownloadPause': '',
	},
	errorNum: 0,//下载错误次数
}

const mutations = {
	setDownloadFileList(state, data) {
		state.downloadFileList = data
	},
	setRaw(state, data) {
		state.raw = data
	},
}

const actions = {
	// 初始化socket
	init(state) {
		state.socket = null
		if (typeof (WebSocket) === "undefined") {
			console.log("WebSocket未初始化")
		} else {
			console.log("init执行")
			// 实例化socket
			state.socket = new WebSocket(state.path)
			// 监听socket连接
			state.socket.onopen = mutations.open
			// 监听socket连接
			state.socket.onclose = mutations.close
			// 监听socket错误信息
			state.socket.onerror = mutations.error
			// 监听socket消息
			state.socket.onmessage = mutations.getMessage
		}
	},
	open() {
		console.log("socket连接成功--", utils.getCurrentDateTime())
		
		state.socketReady = true
	},
	
	close() {
		state.socketReady = false
	},
	
	error() {
		state.socketReady = false
		state.socket = null
		console.log("连接错误--", utils.getCurrentDateTime())
	},
	
	getMessage(msg) {
		console.log("收到消息", msg)
		console.log("msg.data", JSON.parse(msg.data))
		console.log("dateTime", utils.getCurrentDateTime())
		const msgData = JSON.parse(msg.data)
		if (msgData.id) {
			state.downloadFileList.forEach(v => {
				if (+v.fs_id === +msgData.id) {
					v.result = msgData.result
				}
			})
		} else {
			// 修改状态
			state.downloadFileList.forEach((v, index) => {
				// console.log("msgData.params[0]", msgData.params[0])
				if (v.result === msgData.params[0].gid) {
					v.status = state.magStatus[msgData.method]
					//  'aria2.onDownloadStart': 1,//开始
					// 	'aria2.onDownloadPause': -1,//暂停
					// 	'aria2.onDownloadComplete': 2,//完成
					// 	'aria2.onDownloadError': -9, //下载错误
					switch (v.status) {
						case "aria2.onDownloadComplete":
							
							break;
						case "aria2.onDownloadStart": //开始
							// window.$vm.taskNum = --window.$vm.taskNum
							break;
						case "aria2.onDownloadPause":
							// window.$vm.taskNum = ++window.$vm.taskNum
							//下载错误
							break;
						case "aria2.onDownloadError":
							
							break;
					}
					
				}
			})
		}
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
